//
//  ZYBaseAlert.swift
//  ZYUICommon
//
//  Created by Yi Zhou on 2025/1/7.
//

import Foundation
import UIKit

/// 按钮点击响应回调
public typealias ZYAlertHandle = (() ->Void)

/// 点击某一行响应回调
public typealias ZYListAlertHandle = ((_ index: Int) ->Void)

/// 标题和底部按钮的样式元祖（文案，字体，颜色，高度）
public typealias ZYListAlertSettingStyle = (String, UIFont, UIColor, CGFloat)

// MARK: -底部弹窗基类
open class ZYBaseBottomAlert: UIView {
    /// 蒙版
    lazy var maskingView: UIView = {
        return UIView()
            .zyFrame(self.bounds)
            .zyBackgroundColor(UIColor.black.withAlphaComponent(0.4))
    }()
    
    /// 容器
    lazy var contentView: UIView = {
        return UIView()
            .zyFrame(CGRect(x: 0, y: zScreenHeight, width: zScreenWidth, height: contentHeight))
            .zyBackgroundColor(.white)
            .zySeparateCornerRadius(CGRect(x: 0, y: 0, width: zScreenWidth, height: contentHeight), 12, [.topLeft, .topRight])
    }()
    
    /// 蒙版点击收起的手势
    private lazy var tapGesture: UITapGestureRecognizer = {
        let ges = UITapGestureRecognizer(target: self, action: #selector(maskingTapAction))
        ges.numberOfTapsRequired = 1
        ges.numberOfTouchesRequired = 1
        return ges
    }()
    
    /// 容器高度：默认高为屏幕高度一半
    public var contentHeight: CGFloat = zScreenHeight * 0.5 {
        didSet {
            contentView.frame = CGRect(x: 0, y: zScreenHeight, width: zScreenWidth, height: contentHeight)
            contentView.zySeparateCornerRadius(CGRect(x: 0, y: 0, width: zScreenWidth, height: contentHeight), 12, [.topLeft, .topRight])
        }
    }
    
    /// 点击蒙版是否能收起
    public var maskingTouchEnable = true {
        didSet {
            if maskingTouchEnable {
                maskingView.addGestureRecognizer(tapGesture)
            } else {
                maskingView.removeGestureRecognizer(tapGesture)
            }
        }
    }
    
    init() {
        super.init(frame: .zero)
        self.frame = CGRect(x: 0, y: 0, width: zScreenWidth, height: zScreenHeight)
        setupSubviews()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: zScreenWidth, height: zScreenHeight)
        setupSubviews()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func maskingTapAction() {
        close()
    }
    
    /// 设置UI
    open func setupSubviews() {
        addSubview(maskingView)
        addSubview(contentView)
        maskingView.addGestureRecognizer(tapGesture)
    }
    
    /// 弹起弹窗
    /// - Parameter animate: 是否需要动画
    open func show(animate: Bool = true) {
        guard let keyWindown = zKeyWindow else { return }
        keyWindown.addSubview(self)
        if animate {
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut]) { [weak self] in
                self?.contentView.y = zScreenHeight - (self?.contentHeight ?? 0)
            }
        } else {
            contentView.y = zScreenHeight - contentHeight
        }
    }
    
    /// 收起弹窗
    /// - Parameter animate: 是否需要动画
    open func close(animate: Bool = true) {
        if animate {
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut]) { [weak self] in
                self?.contentView.y = zScreenHeight
            } completion: { finish in
                self.removeFromSuperview()
            }
        } else {
            self.removeFromSuperview()
        }
    }
}

// MARK: -中心弹窗基类
open class ZYBaseCenterAlert: UIView {
    /// 蒙版
    lazy var maskingView: UIView = {
        return UIView()
            .zyFrame(self.bounds)
            .zyBackgroundColor(UIColor.black.withAlphaComponent(0.4))
    }()
    
    /// 容器
    lazy var contentView: UIView = {
        return UIView()
            .zyFrame(CGRect(origin: CGPoint(x: (zScreenWidth - contentSize.width) * 0.5, y: (zScreenHeight - contentSize.width) * 0.5), size: contentSize))
            .zyBackgroundColor(UIColor.white)
            .zyAllCornerRadius(12)
    }()
    
    /// 蒙版点击收起的手势
    private lazy var tapGesture: UITapGestureRecognizer = {
        let ges = UITapGestureRecognizer(target: self, action: #selector(maskingTapAction))
        ges.numberOfTapsRequired = 1
        ges.numberOfTouchesRequired = 1
        return ges
    }()
    
    /// 容器size：默认值CGSize(width: mScreenWidth - 80, height: mScreenHeight - 554)
    public var contentSize: CGSize = CGSize(width: zScreenWidth - 80, height: zScreenHeight - 554){
        didSet {
            contentView.frame = CGRect(origin: CGPoint(x: (zScreenWidth - contentSize.width) * 0.5, y: (zScreenHeight - contentSize.height) * 0.5), size: contentSize)
            contentView.zyAllCornerRadius(12)
        }
    }
    
    /// 点击蒙版是否能收起
    public var maskingTouchEnable = true {
        didSet {
            if maskingTouchEnable {
                maskingView.addGestureRecognizer(tapGesture)
            } else {
                maskingView.removeGestureRecognizer(tapGesture)
            }
        }
    }
    
    init() {
        super.init(frame: .zero)
        self.frame = CGRect(x: 0, y: 0, width: zScreenWidth, height: zScreenHeight)
        setupSubviews()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: zScreenWidth, height: zScreenHeight)
        setupSubviews()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func maskingTapAction() {
        close()
    }
    
    /// 设置UI
    open func setupSubviews() {
        addSubview(maskingView)
        addSubview(contentView)
        maskingView.addGestureRecognizer(tapGesture)
    }
    
    /// 弹起弹窗
    /// - Parameter animate: 是否需要动画
    open func show(animate: Bool = true) {
        guard let keyWindown = zKeyWindow else { return }
        keyWindown.addSubview(self)
        contentView.alpha = 0
        if animate {
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut]) { [weak self] in
                self?.contentView.alpha = 1
            }
        } else {
            contentView.alpha = 1
        }
    }
    
    /// 收起弹窗
    /// - Parameter animate: 是否需要动画
    open func close(animate: Bool = true) {
        if animate {
            UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseInOut]) { [weak self] in
                self?.contentView.alpha = 0
            } completion: { finish in
                self.removeFromSuperview()
            }
        } else {
            self.removeFromSuperview()
        }
    }
}

// MARK: -常用确认/取消弹窗(可继承，设置一套默认样式)
open class ZYCommonConfirmationAlert: ZYBaseCenterAlert {
    
    /// 是否显示标题
    public var displayTitle: Bool = true
    
    /// 是否显示副标题
    public var displaySubtitle: Bool = true
    
    /// 按钮个数（只能设置为1和2。如果设置为1，则显示的是左边的按钮。如果设置为其他，则按钮全部隐藏）
    public var buttonNumber: Int = 2
    
    /// 标题font
    public var titleFont: UIFont = UIFont.systemFont(ofSize: 18, weight: .medium)
    
    /// 标题颜色
    public var titleColor: UIColor = ZYUtil.colorWithHex("#333333")
    
    /// 标题对齐方式
    public var titleAlignment: NSTextAlignment = .center
    
    /// 标题文本
    public var titleText: String = "我是主标题"
    
    /// 副标题font
    public var subtitleFont: UIFont = UIFont.systemFont(ofSize: 14, weight: .regular)
    
    /// 副标题颜色
    public var subtitleColor: UIColor = ZYUtil.colorWithHex("#999999")
    
    /// 副标题对齐方式
    public var subtitleAlignment: NSTextAlignment = .center
    
    /// 副标题文本
    public var subtitleText: String = "我是副标题"
    
    /// 左边按钮font
    public var leadingFont: UIFont = UIFont.systemFont(ofSize: 16, weight: .medium)
    
    /// 左边按钮文本颜色
    public var leadingTextColor: UIColor = ZYUtil.colorWithHex("#333333")
    
    /// 左边按钮文本
    public var leadingText: String = "取消"
    
    /// 左边按钮圆角
    public var leadingRadius: CGFloat = 10
    
    /// 左边按钮背景色
    public var leadingBackgroundColor: UIColor = ZYUtil.colorWithHex("#EEEEEE")
    
    /// 右边按钮字体
    public var trailingFont: UIFont = UIFont.systemFont(ofSize: 16, weight: .medium)
    
    /// 右边按钮字体颜色
    public var trailingTextColor: UIColor = UIColor.white
    
    /// 右边按钮文本
    public var trailingText: String = "确认"
    
    /// 右边按钮背景色
    public var trailingBackgroundColor: UIColor = ZYUtil.colorWithHex("#FE3545")
    
    /// 右边按钮圆角
    public var trailingRadius: CGFloat = 10
    
    /// 左间距（一般设计都是居左或者居右对齐，这里按照这种设计来处理）
    public var leading: CGFloat = 24
    
    /// title距上间距
    public var titleTop: CGFloat = 24
    
    /// subtitle距上间距
    public var subtitleTop: CGFloat = 24
    
    /// 按钮距上间距
    public var buttonTop: CGFloat = 24
    
    /// 按钮距底部间距
    public var buttonBottom: CGFloat = 24
    
    /// 按钮size
    public var buttonSize: CGSize = CGSize(width: 116, height: 40)
    
    /// contentView的背景色
    public var contentBackgroundColor: UIColor = UIColor.white
    
    /// contentView的圆角
    public var contentRadius: CGFloat = 12
    
    /// contentView的宽
    public var contentWidth: CGFloat = zScreenWidth - 80
    
    /// 左边按钮点击响应
    public var leadingHandle: ZYAlertHandle?
    
    /// 右边按钮点击响应
    public var trailingHandle: ZYAlertHandle?
    
    /// 主标题
    private lazy var titleLabel: UILabel = {
        return UILabel()
            .zyFont(18, .medium)
            .zyTextColor(titleColor)
            .zyTextAlignment(titleAlignment)
            .zyNumberOfLines(0)
            .zyText(titleText)
    }()
    
    /// 副标题
    private lazy var subtitleLabel: UILabel = {
        return UILabel()
            .zyFont(14, .regular)
            .zyTextColor(subtitleColor)
            .zyTextAlignment(subtitleAlignment)
            .zyNumberOfLines(0)
            .zyText(subtitleText)
    }()
    
    /// 左边按钮
    private lazy var leadingButton: UIButton = {
        return UIButton(type: .custom)
            .zyBackgroundColor(leadingBackgroundColor)
            .zyFont(16, .medium)
            .zyNormalTextColor(leadingTextColor)
            .zyNormalText(leadingText)
            .zyAllCornerRadius(leadingRadius)
            .zyAddTarget { [weak self] in
                self?.leadingHandle?()
                self?.close()
            }
    }()
    
    /// 右边按钮
    private lazy var trailingButton: UIButton = {
        return UIButton(type: .custom)
            .zyBackgroundColor(trailingBackgroundColor)
            .zyFont(16, .medium)
            .zyNormalTextColor(trailingTextColor)
            .zyNormalText(trailingText)
            .zyAllCornerRadius(trailingRadius)
            .zyAddTarget { [weak self] in
                self?.trailingHandle?()
                self?.close()
            }
    }()
    
    public override func setupSubviews() {
        super.setupSubviews()
        maskingTouchEnable = false
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(subtitleLabel)
        contentView.addSubview(leadingButton)
        contentView.addSubview(trailingButton)
        
        layoutAlert()
    }
    
    /// 属性设置完毕，调用该方法更新属性和布局，否则不会生效
    public func layoutAlert() {
        
        var titleHeight: CGFloat = 0
        if !displayTitle {
            titleTop = 0
            titleLabel.isHidden = true
        } else {
            titleHeight = ZYUtil.stringHeight(titleText, titleFont, contentWidth - leading * 2)
        }
        
        var subtitleHeight: CGFloat = 0
        if !displaySubtitle {
            subtitleTop = 0
            subtitleLabel.isHidden = true
        } else {
            subtitleHeight = ZYUtil.stringHeight(subtitleText, subtitleFont, contentWidth - leading * 2)
        }
        
        let contentHeight = titleTop + titleHeight + subtitleTop + subtitleHeight + buttonTop + buttonSize.height + buttonBottom
        
        contentSize = CGSize(width: contentWidth, height: contentHeight)
        contentView.zyBackgroundColor(contentBackgroundColor).zyAllCornerRadius(contentRadius)
        
        titleLabel
            .zyFrame(CGRect(x: leading, y: titleTop, width: contentWidth - leading * 2, height: titleHeight))
            .zyTextColor(titleColor)
            .zyText(titleText)
            .zyTextAlignment(titleAlignment)
        titleLabel.font = titleFont
        
        subtitleLabel
            .zyFrame(CGRect(x: leading, y: titleTop + titleHeight + subtitleTop, width: contentWidth - leading * 2, height: subtitleHeight))
            .zyTextColor(subtitleColor)
            .zyText(subtitleText)
            .zyTextAlignment(subtitleAlignment)
        subtitleLabel.font = subtitleFont
        
        switch buttonNumber {
        case 1:
            leadingButton
                .zyFrame(CGRect(x: leading, y: titleTop + titleHeight + subtitleTop + subtitleHeight + buttonTop, width: buttonSize.width, height: buttonSize.height))
                .zyBackgroundColor(leadingBackgroundColor)
                .zyNormalTextColor(leadingTextColor)
                .zyNormalText(leadingText)
                .zyAllCornerRadius(leadingRadius)
            leadingButton.titleLabel?.font = leadingFont
            trailingButton.isHidden = true
        case 2:
            leadingButton
                .zyFrame(CGRect(x: leading, y: titleTop + titleHeight + subtitleTop + subtitleHeight + buttonTop, width: buttonSize.width, height: buttonSize.height))
                .zyBackgroundColor(leadingBackgroundColor)
                .zyNormalTextColor(leadingTextColor)
                .zyNormalText(leadingText)
                .zyAllCornerRadius(leadingRadius)
            leadingButton.titleLabel?.font = leadingFont
            trailingButton
                .zyFrame(CGRect(x: contentWidth - leading - buttonSize.width, y: titleTop + titleHeight + subtitleTop + subtitleHeight + buttonTop, width: buttonSize.width, height: buttonSize.height))
                .zyBackgroundColor(trailingBackgroundColor)
                .zyNormalTextColor(trailingTextColor)
                .zyNormalText(trailingText)
                .zyAllCornerRadius(trailingRadius)
            leadingButton.titleLabel?.font = trailingFont
        default:
            leadingButton.isHidden = true
            trailingButton.isHidden = true
        }
    }
    
}

// MARK: -常用列表弹窗(可继承，设置一套默认样式)
open class ZYCommonListAlert: ZYBaseBottomAlert, UITableViewDataSource, UITableViewDelegate {
    
    /// 列表数据源
    public var dataSource = [String]()
    
    /// 是否展示标题
    public var displayTitle: Bool = true
    
    /// 列表字体
    public var textFont: CGFloat = 16
    
    /// 列表文本颜色
    public var textColor: UIColor = ZYUtil.colorWithHex("#333333")
    
    /// 列表字体对齐方式
    public var textAlinment: NSTextAlignment = .center
    
    /// 列表行高
    public var rowHeight: CGFloat = 44
    
    /// 列表是否显示分割线
    public var singleLine: Bool = true
    
    /// 列表文字居左距离
    public var leading: CGFloat = 20
    
    /// 取消按钮上方分割线高度
    public var separatorHeight: CGFloat = 10
    
    /// 取消按钮上方分割线颜色
    public var separatorColor: UIColor = ZYUtil.colorWithHex("#F7F7F7")
    
    /// 取消按钮样式
    public var cancelStyle: ZYListAlertSettingStyle?
    
    /// 标题样式
    public var titleStyle: ZYListAlertSettingStyle?
    
    /// 点击列表某一行响应
    public var didSelectRowAtHandle: ZYListAlertHandle?
    
    private lazy var titleLabel: UILabel = {
        return UILabel()
            .zyFrame(CGRect(x: 0, y: 0, width: zScreenWidth, height: rowHeight))
            .zyFont(18, .medium)
            .zyTextColor(textColor)
            .zyTextAlignment(.center)
            .zyText("我是标题")
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: zScreenWidth, height: contentHeight - zSafeBottomMargin - rowHeight - separatorHeight))
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = .white
        tableView.register(ZYCommonListAlertCell.self, forCellReuseIdentifier: ZYCommonListAlertCell.className)
        return tableView
    }()
    
    private lazy var separatorView: UIView = {
        return UIView(frame: CGRect(x: 0, y: contentHeight - zSafeBottomMargin - separatorHeight, width: zScreenWidth, height: separatorHeight)).zyBackgroundColor(ZYUtil.colorWithHex("#F7F7F7"))
    }()
    
    private lazy var cancelButton: UIButton = {
        return UIButton()
            .zyFrame(CGRect(x: 0, y: contentHeight - zSafeBottomMargin - rowHeight, width: zScreenWidth, height: rowHeight))
            .zyFont(textFont)
            .zyNormalTextColor(textColor)
            .zyNormalText("取消")
            .zyAddTarget { [weak self] in
                self?.close()
            }
    }()
    
    public override func setupSubviews() {
        super.setupSubviews()
        contentView.addSubview(titleLabel)
        contentView.addSubview(tableView)
        contentView.addSubview(separatorView)
        contentView.addSubview(cancelButton)
    }
    
    public func layoutAlert() {
        
        var titleText = "我是标题"
        var titleFont = UIFont.systemFont(ofSize: textFont)
        var titleTextColor = textColor
        var titleHeight = rowHeight
        if let tstyle = titleStyle {
            titleText = tstyle.0
            titleFont = tstyle.1
            titleTextColor = tstyle.2
            titleHeight = tstyle.3
        }
        
        var cancelText = "取消"
        var cancelFont = UIFont.systemFont(ofSize: textFont)
        var cancelTextColor = textColor
        var cancelHeight = rowHeight
        if let cstyle = cancelStyle {
            cancelText = cstyle.0
            cancelFont = cstyle.1
            cancelTextColor = cstyle.2
            cancelHeight = cstyle.3
        }
        
        if !displayTitle {
            titleLabel.isHidden = true
            titleHeight = 0
        }
        
        let tabHeight = CGFloat(dataSource.count) * rowHeight
        contentHeight = zSafeBottomMargin + cancelHeight + separatorHeight + tabHeight + titleHeight
        titleLabel.height = titleHeight
        tableView.y = titleHeight
        tableView.height = tabHeight
        separatorView.y = titleHeight + tabHeight
        separatorView.height = separatorHeight
        cancelButton.y = titleHeight + tabHeight + separatorHeight
        cancelButton.height = cancelHeight
        
        titleLabel.font = titleFont
        titleLabel.textColor = titleTextColor
        titleLabel.text = titleText
        
        separatorView.backgroundColor = separatorColor
        
        cancelButton.titleLabel?.font = cancelFont
        cancelButton.zyNormalText(cancelText).zyNormalTextColor(cancelTextColor)
        
        tableView.reloadData()
    }
    
    //MARK: -
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ZYCommonListAlertCell.className, for: indexPath) as! ZYCommonListAlertCell
        cell.titleLabel.text = dataSource[indexPath.row]
        cell.titleLabel.font = UIFont.systemFont(ofSize: textFont)
        cell.titleLabel.textColor = textColor
        cell.titleLabel.textAlignment = textAlinment
        cell.titleLabel.x = leading
        cell.titleLabel.width = zScreenWidth - leading * 2
        cell.lineView.backgroundColor = separatorColor
        cell.lineView.isHidden = !singleLine
        cell.cellHeight = rowHeight
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        didSelectRowAtHandle?(indexPath.row)
        close()
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return rowHeight
    }
    
    //MARK: -
    private class ZYCommonListAlertCell: UITableViewCell {
        
        var cellHeight: CGFloat = 0 {
            didSet {
                titleLabel.height = cellHeight
                lineView.y = cellHeight - 0.5
            }
        }
        
        private(set) lazy var titleLabel: UILabel = {
            return UILabel()
                .zyFrame(CGRect(x: 0, y: 0, width: zScreenWidth, height: cellHeight))
                .zyFont(16)
                .zyTextAlignment(.center)
                .zyTextColor(ZYUtil.colorWithHex("#333333"))
        }()
        
        private(set) lazy var lineView: UIView = {
            return UIView()
                .zyFrame(CGRect(x: 0, y: cellHeight - 0.5, width: zScreenWidth, height: 0.5))
                .zyBackgroundColor(ZYUtil.colorWithHex("#F7F7F7"))
        }()
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.selectionStyle = .none
            self.backgroundColor = .white
            contentView.addSubview(titleLabel)
            contentView.addSubview(lineView)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}
